import { createHashRouter, redirect } from "react-router-dom";
import App from "./App";
import { isLogin } from "./utils/utils";
import { ApiGetHomeData } from "./utils/api";
import { Toast } from "antd-mobile";

import Home from "./pages/home";
import Quick from "./pages/quick";
import User from "./pages/user";
import Login from "./pages/login";
import Register from "./pages/register";
import Toggle from "./pages/toggle";
import Pratice from "./pages/pratice";
import Qdtest from "./pages/qdtest";

const router = createHashRouter([
  {
    path: "/",
    element: <App />, // 根组件 outlet
    loader(params) {
      // if (/\/$/.test(params.request.url)) {
      //   return redirect("/home");
      // }
      // console.log(params);
    },
    children: [
      // -----------------------------------------------------------------
      // 首页
      {
        // 设置index为true的时候，path就不需要设置，该选项就变成首页/
        index: true, // 索引的意思
        element: <Home />,
        async loader() {
          // 请求接口的异步函数
          // 执行优先级更高，未进入页面的时候，已经执行
          const getData = async () => {
            let res = await ApiGetHomeData();
            if (res.errCode !== 0) {
              Toast.show({
                icon: "fail",
                content: res.message,
              });
              return;
            }
            return res.data;
          };

          return { getData };
        },
      },
      // 切换考试题目
      {
        path: "toggle",
        element: <Toggle />,
      },
      // 练习
      {
        path: "pratice",
        element: <Pratice />,
      },
      // -----------------------------------------------------------------

      // 快速刷题
      {
        path: "quick",
        element: <Quick />,
        loader() {},
      },
      // 用户中心
      {
        path: "user",
        element: <User />,
        loader() {
          // 当用户未登录的时候，跳转到登录页
          if (!isLogin()) {
            return redirect("/login");
          }
        },
      },
      // 登录页
      {
        path: "login",
        element: <Login />,
      },
      // 注册页
      {
        path: "register",
        element: <Register />,
      },
      // 练习页面
      {
        path: "qdtest",
        element: <Qdtest />,
      },
    ],
  },
]);

export default router;
